﻿Public Class FrmOrdenCompra

    Dim controller As New Class_RC_Controller.rc_OrdenCompra
    Dim proveedores As New Class_RC_Controller.rc_Proveedores
    Dim clientes As New Class_RC_Controller.rc_Clientes
    Dim mante As New Class_RC_Controller.rc_Mantenimiento
    Dim materiales As New Class_RC_Controller.rc_Materiales

    Private _codOrden As Integer = 0

    Public Property codOrden() As Integer
        Get
            Return _codOrden
        End Get
        Set(value As Integer)
            _codOrden = value
            txtcodigo.Text = value.ToString().PadLeft(4, "0")
        End Set
    End Property

    Private Sub llenarCombos()

        cboEstado.SelectedIndex = 0

        Dim ds As DataTable
        ds = proveedores.get_Proveedores_All(oiml.dbConn, 0, "", "", 0)
        With Me.cboProveedor
            .DataSource = ds
            .DisplayMember = "nombre"
            .ValueMember = "codProveedor"
        End With

        Dim dsResp As DataTable
        dsResp = clientes.get_vendedores(oiml.dbConn)
        With Me.cboResponsable
            .DataSource = dsResp
            .DisplayMember = "usuario"
            .ValueMember = "codUsuario"
        End With

        Dim dsTipo As DataTable
        dsTipo = materiales.get_tipo_Materiales(oiml.dbConn)
        With Me.cboTipoMaterial
            .DataSource = dsTipo
            .DisplayMember = "descTipoMaterial"
            .ValueMember = "codTipoMaterial"
        End With

        CargarMateriales()

    End Sub

    Private Sub CargarMateriales()

        Dim codTipoMat As Integer = 0

        If cbxTipo.Checked And IsNumeric(cboTipoMaterial.SelectedValue) Then
            codTipoMat = cboTipoMaterial.SelectedValue

            Dim dt As New DataTable
            dt = materiales.get_Materiales_All(oiml.dbConn, 0, txtMaterial.Text, codTipoMat)

            If Not dt Is Nothing Then

                With Me.cboMateriales
                    .DataSource = dt
                    .DisplayMember = "DescMaterial"
                    .ValueMember = "codMaterial"
                End With
            Else
                cboMateriales.DataSource = Nothing
            End If

        End If

        

    End Sub

    Private Sub CargarMateriales_ByID(codMaterial As Integer)

        Dim dt As New DataTable
        dt = materiales.get_Materiales_All(oiml.dbConn, codMaterial, "", 0)

        If Not dt Is Nothing Then

        Else

        End If

    End Sub

    Private Sub CargarDetalles()
        If codOrden > 0 Then

            Dim dt As New DataTable
            dt = controller.get_OrdenCompra_Detalles_All(oiml.dbConn, codOrden)
            If Not dt Is Nothing Then
                dgvdetalle.DataSource = dt
            Else
                dgvdetalle.DataSource = ""
            End If

        End If

    End Sub

    Private Sub CargarOrden()
        Try

            If codOrden > 0 Then

                Dim ds As New DataTable
                ds = controller.get_OrdenCompra_ByID(oiml.dbConn, codOrden)

                If Not ds Is Nothing Then

                    ' cargar los controles del formulario con los valores de los campos del registro
                    codOrden = ds.Rows(0)("codOrdenCompra").ToString
                    Me.txtNroOrden.Text = ds.Rows(0)("nroOrdenCompra").ToString

                    If txtNroOrden.Text <> "" Then
                        txtNroOrden.ReadOnly = True
                        'txtcantidad.ReadOnly = True
                    Else
                        txtNroOrden.ReadOnly = False
                        'txtcantidad.ReadOnly = False
                    End If

                    Me.fechaOrden.Value = DateTime.Parse(ds.Rows(0)("fecha").ToString())
                    Me.cboEstado.Text = ds.Rows(0)("estadoOrdenCompra").ToString
                    Me.cboResponsable.SelectedValue = ds.Rows(0)("codResponsable").ToString
                    Me.cboProveedor.SelectedValue = ds.Rows(0)("codProveedor").ToString
                    Me.lblUsuario.Text = ds.Rows(0)("usuario").ToString
                    Me.lblfechaActualizacion.Text = ds.Rows(0)("fechaActualizacion_").ToString

                    CargarDetalles()
                    ControlEstado()

                End If

            Else

                ' cargar los controles del formulario con los valores de los campos del registro
                codOrden = 0
                Me.txtNroOrden.Text = ""
                Me.fechaOrden.Value = DateTime.Now
                Me.cboProveedor.SelectedIndex = 0
                Me.cboResponsable.SelectedIndex = 0
                Me.cboEstado.SelectedIndex = 0

                lblUsuario.Text = oiml.Usuario
                lblfechaActualizacion.Text = Date.Now.ToShortDateString
                txtNroOrden.Focus()

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Private Sub ControlEstado()
        If Me.cboEstado.Text = "APROBADA" Or Me.cboEstado.Text = "ANULADA" Then
            grbCabecera.Enabled = False
            grbDetalle.Enabled = False
        Else

            If controller.Update_OrdenCompra(oiml.dbConn, codOrden, fechaOrden.Value,
                                             Integer.Parse(cboProveedor.SelectedValue), txtNroOrden.Text,
                                             Integer.Parse(cboResponsable.SelectedValue), cboEstado.Text, oiml.idUsuario) = False Then
                MessageBox.Show("Error: " & controller.MessageError.Message, "Ordenes", MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Sub
            End If

        End If
    End Sub

    Private Shadows Sub KeyUpmask(ByVal MaskedTextboxs As System.Windows.Forms.MaskedTextBox, ByVal e As System.Windows.Forms.KeyEventArgs)

        'Teclas que Utilizaremos El cual solo son las numericas
        If e.KeyData = Keys.Space Or e.KeyData = Keys.Decimal Or _
         e.KeyData = Keys.NumPad0 Or e.KeyData = Keys.NumPad1 Or e.KeyData = Keys.NumPad2 Or e.KeyData = Keys.NumPad3 _
           Or e.KeyData = Keys.NumPad4 Or e.KeyData = Keys.NumPad5 Or e.KeyData = Keys.NumPad6 Or _
           e.KeyData = Keys.NumPad7 Or e.KeyData = Keys.NumPad8 Or e.KeyData = Keys.NumPad9 _
           Or e.KeyData = Keys.D0 Or e.KeyData = Keys.D1 Or e.KeyData = Keys.D2 Or e.KeyData = Keys.D3 Or _
           e.KeyData = Keys.D4 Or e.KeyData = Keys.D5 Or e.KeyData = Keys.D6 _
           Or e.KeyData = Keys.D7 Or e.KeyData = Keys.D8 Or e.KeyData = Keys.D9 Or e.KeyData = Keys.Tab Or e.KeyData = Keys.Enter _
            Then

            'Programamos la tecla de Retroceso en el textbox
        ElseIf e.KeyData = Keys.Back And MaskedTextboxs.Text.Length > 0 Then
            On Error Resume Next
            'Removemos un caracter mediante se presione la tecla Back
            MaskedTextboxs.Text.Remove(MaskedTextboxs.SelectionStart - 1)

            'si el textbox es menor que un caracter
        ElseIf MaskedTextboxs.Text.Length < 1 Then
            'ponemos el textbox En Blanco
            MaskedTextboxs.Text = String.Empty
            'ponemos la variable    NumerosYaescritos en Blanco

        Else
            'ponemos el textbox enblanco
            MaskedTextboxs.Text = String.Empty
            'Hacemos Sonar un Beep para indicarle al usuario que ha presionado un caracter y no un Numero
            Beep()
            MsgBox("Introducir solo valores numericos")
        End If

    End Sub

    Private Shadows Sub KeyUp(ByVal TextBoxs As System.Windows.Forms.TextBox, ByVal e As System.Windows.Forms.KeyEventArgs)

        'Teclas que Utilizaremos El cual solo son las numericas
        If e.KeyData = Keys.Space Or e.KeyData = Keys.Decimal Or _
         e.KeyData = Keys.NumPad0 Or e.KeyData = Keys.NumPad1 Or e.KeyData = Keys.NumPad2 Or e.KeyData = Keys.NumPad3 _
           Or e.KeyData = Keys.NumPad4 Or e.KeyData = Keys.NumPad5 Or e.KeyData = Keys.NumPad6 Or _
           e.KeyData = Keys.NumPad7 Or e.KeyData = Keys.NumPad8 Or e.KeyData = Keys.NumPad9 _
           Or e.KeyData = Keys.D0 Or e.KeyData = Keys.D1 Or e.KeyData = Keys.D2 Or e.KeyData = Keys.D3 Or _
           e.KeyData = Keys.D4 Or e.KeyData = Keys.D5 Or e.KeyData = Keys.D6 _
           Or e.KeyData = Keys.D7 Or e.KeyData = Keys.D8 Or e.KeyData = Keys.D9 Or e.KeyData = Keys.Tab Or e.KeyData = Keys.Enter _
           Or e.KeyData = Keys.OemMinus Then

            'Programamos la tecla de Retroceso en el textbox
        ElseIf e.KeyData = Keys.Back And TextBoxs.Text.Length > 0 Then
            On Error Resume Next
            'Removemos un caracter mediante se presione la tecla Back
            TextBoxs.Text.Remove(TextBoxs.SelectionStart - 1)

            'si el textbox es menor que un caracter
        ElseIf TextBoxs.Text.Length < 1 Then
            'ponemos el textbox En Blanco
            TextBoxs.Text = String.Empty
            'ponemos la variable    NumerosYaescritos en Blanco

        Else
            'ponemos el textbox enblanco
            TextBoxs.Text = String.Empty
            'Hacemos Sonar un Beep para indicarle al usuario que ha presionado un caracter y no un Numero
            Beep()
            MsgBox("Introducir solo valores numericos")
        End If

    End Sub

    Private Sub FrmVentas_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        Me.dgvdetalle.AutoGenerateColumns = False
        Me.llenarCombos()
        Me.CargarOrden()

    End Sub

    Private Function ValidarCampos() As Boolean

        Dim controlCampos As Boolean = False

        'If txtNroOrden.Text = "" Then
        '    ErrorProvider.SetError(txtNroOrden, "Campo obligatorio")
        '    controlCampos = True
        'Else
        '    ErrorProvider.SetError(txtNroOrden, "")
        'End If

        If fechaOrden.Value.ToString = "" Then
            ErrorProvider.SetError(fechaOrden, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider.SetError(fechaOrden, "")
        End If

        If Not IsNumeric(cboProveedor.SelectedValue) Then
            ErrorProvider.SetError(cboProveedor, "Campo numerico, cantidad")
            controlCampos = True
        Else
            ErrorProvider.SetError(cboProveedor, "")
        End If        '

        If Not IsNumeric(cboResponsable.SelectedValue) Then
            ErrorProvider.SetError(cboResponsable, "Campo numerico, cantidad")
            controlCampos = True
        Else
            ErrorProvider.SetError(cboResponsable, "")
        End If        '
        '
        Return controlCampos

    End Function

    Private Function ValidarDetallesCampos() As Boolean

        Dim controlCampos As Boolean = False

        If Not IsNumeric(txtcantidad.Text) Then
            ErrorProvider.SetError(txtcantidad, "Campo numerico, cantidad")
            controlCampos = True
        Else
            ErrorProvider.SetError(txtcantidad, "")
        End If        '

        If Not IsNumeric(cboMateriales.SelectedValue) Then
            ErrorProvider.SetError(cboMateriales, "Campo numerico, cantidad")
            controlCampos = True
        Else
            ErrorProvider.SetError(cboMateriales, "")
        End If        '

        Return controlCampos

    End Function

    Private Sub btncancelar_Click(sender As System.Object, e As System.EventArgs) Handles btnCancelar.Click
        Me.Close()
    End Sub

    Private Sub btnAgregarDetalle_Click(sender As System.Object, e As System.EventArgs) Handles btnAgregarDetalle.Click
        Try

            If ValidarDetallesCampos() Then
                MessageBox.Show("Falta llenar datos del detalle", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1)
                txtcantidad.Focus()
            Else

                If codOrden = 0 Then

                    If ValidarCampos() Then
                        'txtNroOrden.Focus()
                        Exit Sub
                    Else

                        codOrden = controller.Insert_OrdenCompra(oiml.dbConn, fechaOrden.Value,
                                             Integer.Parse(cboProveedor.SelectedValue), txtNroOrden.Text,
                                             Integer.Parse(cboResponsable.SelectedValue), cboEstado.Text, oiml.idUsuario)

                        If codOrden = 0 Then
                            MessageBox.Show("Error: " & controller.MessageError.Message, "Ordenes", MessageBoxButtons.OK, MessageBoxIcon.Error)
                            Exit Sub
                        End If

                    End If

                Else

                    If ValidarCampos() Then
                        txtNroOrden.Focus()
                        Exit Sub
                    Else

                        If controller.Update_OrdenCompra(oiml.dbConn, codOrden, fechaOrden.Value,
                                             Integer.Parse(cboProveedor.SelectedValue), txtNroOrden.Text,
                                             Integer.Parse(cboResponsable.SelectedValue), cboEstado.Text, oiml.idUsuario) = False Then
                            MessageBox.Show("Error: " & controller.MessageError.Message, "Ordenes", MessageBoxButtons.OK, MessageBoxIcon.Error)
                            Exit Sub
                        End If

                    End If

                End If

                If codOrden > 0 Then
                    If controller.Insert_OrdenCompra_Detalle(oiml.dbConn, codOrden, Integer.Parse(cboMateriales.SelectedValue), Decimal.Parse(txtcantidad.Text)) Then
                        CargarOrden()
                        limpiarDetalles()

                    Else
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Ordenes", MessageBoxButtons.OK, MessageBoxIcon.Error)

                    End If

                End If

            End If

        Catch ex As Exception
            MsgBox(ex.Message)

        End Try

        txtcantidad.Text = 1

    End Sub

    Public Sub limpiarDetalles()
        txtcantidad.Text = 1
        txtMaterial.Text = ""
    End Sub

    Private Sub btnEliminarDetalle_Click(sender As System.Object, e As System.EventArgs) Handles btnEliminarDetalle.Click
        Try
            If dgvdetalle.SelectedRows.Count > 0 Then
                Dim codorden As Integer
                Dim codmaterial As Integer
                codorden = dgvdetalle.SelectedRows(0).Cells(0).Value
                codmaterial = dgvdetalle.SelectedRows(0).Cells(1).Value

                If codorden > 0 And MessageBox.Show("Desea eliminar el registro seleccionado?", "Ordenes", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                    If controller.Delete_OrdenCompra_Detalle(oiml.dbConn, codorden, codmaterial) Then
                        CargarDetalles()
                        dgvdetalle.Refresh()
                    Else
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Ordenes", MessageBoxButtons.OK, MessageBoxIcon.Error)

                    End If

                End If

            End If

        Catch ex As Exception
            MsgBox(ex.Message)

        End Try

    End Sub

    Private Sub btnGrabar_Click(sender As System.Object, e As System.EventArgs) Handles btnGrabar.Click

        If ValidarCampos() Then
            txtNroOrden.Focus()
            Exit Sub
        End If

        If codOrden = 0 Then

            codOrden = controller.Insert_OrdenCompra(oiml.dbConn, fechaOrden.Value,
                                             Integer.Parse(cboProveedor.SelectedValue), txtNroOrden.Text,
                                             Integer.Parse(cboResponsable.SelectedValue), cboEstado.Text, oiml.idUsuario)

            If codOrden > 0 Then
                MessageBox.Show("Registro grabado con exito!", "Ordenes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Me.DialogResult = Windows.Forms.DialogResult.OK
                Me.Close()

            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Ordenes", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        Else
            If controller.Update_OrdenCompra(oiml.dbConn, codOrden, fechaOrden.Value,
                                             Integer.Parse(cboProveedor.SelectedValue), txtNroOrden.Text,
                                             Integer.Parse(cboResponsable.SelectedValue), cboEstado.Text, oiml.idUsuario) Then

                MessageBox.Show("Registro grabado con exito!", "Ordenes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Me.DialogResult = Windows.Forms.DialogResult.OK
                Me.Close()

            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Ordenes", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        End If

    End Sub

    Private Sub btneliminar_Click(sender As System.Object, e As System.EventArgs) Handles btnEliminar.Click

        Try
            If codOrden > 0 Then
                If MessageBox.Show("Desea eliminar el registro seleccionado?", "Ordenes", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                    If controller.Delete_OrdenCompra(oiml.dbConn, codOrden) Then
                        Me.Close()

                    Else
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Ordenes", MessageBoxButtons.OK, MessageBoxIcon.Error)

                    End If

                End If
            End If


        Catch ex As Exception
            MsgBox(ex.Message)

        End Try

    End Sub

    Private Sub cbxTipo_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles cbxTipo.CheckedChanged
        CargarMateriales()
    End Sub

    Private Sub cboTipoMaterial_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles cboTipoMaterial.KeyDown
        If e.KeyCode = Keys.Enter Then
            CargarMateriales()
        End If
    End Sub

    Private Sub txtMaterial_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles txtMaterial.KeyDown
        If e.KeyCode = Keys.Enter Then
            CargarMateriales()
        End If
    End Sub

    Private Sub cboTipoMaterial_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cboTipoMaterial.SelectedValueChanged

        CargarMateriales()

    End Sub
    Private m_frmRpts As FormReportes
    Public Property frmRpts() As FormReportes
        Get
            Return m_frmRpts
        End Get
        Set(ByVal value As FormReportes)
            m_frmRpts = value
        End Set
    End Property

    Private Function ImprimirOrden()

        Dim classController As New Class_RC_Controller.rc_OrdenCompra()

        Dim dt As New DataTable
        dt = classController.get_OrdenCompra_Impresion_ByID(oiml.dbConn, codOrden)

        If Not dt Is Nothing Then
            Return dt
        Else
            MessageBox.Show("Error: " & classController.MessageError.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return Nothing
        End If
    End Function

    Private Sub btnImprimir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImprimir.Click

        If frmRpts Is Nothing Then
            frmRpts = New FormReportes()
            'frmRpts.MdiParent = Me
            frmRpts.tipo_Reporte = "IMPRIMIRORDEN"
            frmRpts.datos_Reporte = ImprimirOrden()
            frmRpts.ShowDialog()
        Else

            If Not frmRpts.Visible Then
                frmRpts = New FormReportes()
                'frmRpts.MdiParent = Me
                frmRpts.tipo_Reporte = "IMPRIMIRORDEN"
                frmRpts.datos_Reporte = ImprimirOrden()
                frmRpts.ShowDialog()
            Else
                frmRpts.tipo_Reporte = "IMPRIMIRORDEN"
                frmRpts.datos_Reporte = ImprimirOrden()
                frmRpts.Select()
                frmRpts.Activate()
            End If

        End If

        If Not controller.MessageError Is Nothing Then
            MessageBox.Show("Error: " & controller.MessageError.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If

    End Sub

    Private Sub btnAnular_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAnular.Click
        Try
            If codOrden > 0 Then
                If MessageBox.Show("Desea Anular la Orden de Compra Seleccionada?", "Compras", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                    If controller.Update_OrdenCompra_Estado(oiml.dbConn, codOrden, "ANULADA", oiml.idUsuario) Then
                        Me.Close()

                    Else
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

                    End If

                End If
            End If


        Catch ex As Exception
            MsgBox(ex.Message)

        End Try
    End Sub

  
End Class